<template>
  <div v-if="success" class="vue-flowchart-editor-container">
    <flowAlgorithmEditor
      :key="reRender"
      :flowchart-id="12"
      :read-only="readOnly"
      :chart-data="flowChartData"
      :algorithm-category-list="algorithmCategoryList"
      :savebeforerun="savebeforerun"
      @save-data="save"
    />
  </div>
</template>

<script>
  import flowAlgorithmEditor from './flowAlgorithmEditor'
  import chartData from './data'
  // 左侧算法列表
  import algorithmCategoryList from './algorithmCategoryItems'
  import cloneDeep from 'lodash/cloneDeep'
  import axios from 'axios'
  import './iconfont'

  export default {
    name: 'VueFlowchartEditorDemo',
    components: {
      flowAlgorithmEditor
    },
    data() {
      return {
        readOnly: !true,
        reRender: +new Date(),
        flowChartData: {},
        algorithmCategoryList: algorithmCategoryList,
        success: true
      }
    },
    created() {
      console.log('enter flow demo create')
      // const id = this.$route.params && this.$route.params.id  // id是在flowList中点击对应的flowchart后跳转到对应界面后在url最后一个/后的id
      this.loadFlowchart()
    },
    mounted() {
      this.$on('toggle-read-only', () => {
        this.readOnly = !this.readOnly
        this.$nextTick(() => {
          console.log(this.readOnly)
          this.reRender = +new Date()
        })
      })
    },

    methods: {
      loadFlowchart() {
        this.flowChartData = {
          id: 12,
          name: 123123414,
          nodes: [],
          edges: []
      }
        this.success = true
        // axios
        //   .get(`/api/datalab/flowchart/${id}`) // get 是向服务器发送索取请求${id}的作用是 在$后边插入一个js变量  .then处理 get之后返回的结果
        //   .then((res) => {
        //     this.flowChartData = {
        //       id: res.data.id,
        //       name: res.data.name,
        //       nodes: JSON.parse(res.data.nodes),
        //       edges: JSON.parse(res.data.edges)
        //     }
        //     this.success = true
        //     this.readOnly = res.data.read_only
        //   })
        //   .catch((err) => {
        //     console.log(err)
        //   })
      },
      async save(data) {
        // 在这里写数据保存逻辑
        console.log('save data')
        try {
          const response = await axios.put(//put 是向服务器发送修改请求
            `/api/datalab/flowchart/${this.flowChartData.id}`,
            {
              read_only: this.readOnly,
              nodes: data.nodes ? JSON.stringify(data.nodes) : '[]',
              edges: data.edges ? JSON.stringify(data.edges) : '[]'
            }
          )
          console.log(response)
        } catch (err) {
          console.log(err)
        }
      },
      async savebeforerun(data) {
        this.readOnly = true
        await this.save(data)
      }
    }
  }
</script>

<style global>
</style>

<style>
  .vue-flowchart-editor-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    margin: 0;
    padding: 0;
  }
</style>
